<template>
  <n-modal id="basic-modal" style="padding: 40px 30px" v-bind="getBindValue" v-model:show="isModal"
           @close="onCloseModal">
    <template #header>
      <div class="w-full cursor-move" id="basic-modal-bar">
        {{ getBindValue.title }}
      </div>
    </template>
    <template #default>
      <slot name="default"></slot>
    </template>
    <template #action v-if="!$slots.action">
      <n-space>
        <n-button @click="closeModal">取消</n-button>
        <n-button type="primary" :loading="subLoading" @click="handleSubmit($event)">{{
            subBtuText
          }}
        </n-button>
      </n-space>
    </template>
    <template v-else #action>
      <slot name="action"></slot>
    </template>
  </n-modal>
</template>

<script lang="ts" setup>
import {
  getCurrentInstance,
  ref,
  unref,
  computed,
  useAttrs
} from 'vue';
import { NGradientText } from 'naive-ui';
import { basicProps } from './props';

import { deepMerge } from '../../../utils/common';

import { ModalProps, ModalMethods } from './type';

const attrs = useAttrs(); // 获取属性值
const props = defineProps({ ...basicProps });
const emit = defineEmits(['on-close', 'on-ok', 'register']);

const propsRef = ref(null);

const isModal = ref(false);
const subLoading = ref(false);


const subBtuText = computed(() => {
  const { subBtuText } = propsRef.value as any;
  return subBtuText || props.subBtuText;
});

async function setProps(modalProps: Partial<ModalProps>): Promise<void> {
  propsRef.value = deepMerge(unref(propsRef) || ({} as any), modalProps);
}

const getProps = computed((): any => {
  return { ...props, ...(unref(propsRef) as any) };
});

const getBindValue = computed(() => {
  return {
    ...attrs,
    ...unref(getProps),
    ...unref(<object> propsRef),
  };
});

function setSubLoading(status: boolean) {
  subLoading.value = status;
}

function openModal() {
  isModal.value = true;
}

function closeModal() {
  isModal.value = false;
  subLoading.value = false;
  emit('on-close');
}

function onCloseModal() {
  isModal.value = false;
  emit('on-close');
}

function handleSubmit(event: Event) {
  subLoading.value = true;
  emit('on-ok', event);
}

const modalMethods: ModalMethods = {
  setProps,
  openModal,
  closeModal,
  setSubLoading,
};

const instance = getCurrentInstance();
instance && emit('register', modalMethods);
</script>

<style>
/*.cursor-move {*/
/*  cursor: move;*/
/*}*/
#basic-modal-bar{
font-size: 16px;
}
</style>
